package ac.github.oa.internal.core.item.random

import ac.github.oa.api.common.script.InlineScriptContext
import ac.github.oa.api.common.script.StringScript
import ac.github.oa.util.rebuild
import org.bukkit.Color
import taboolib.common.util.asList
import taboolib.common5.Coerce
import taboolib.platform.util.ItemBuilder
import java.util.*

class RandomFactor(val context: InlineScriptContext) {

    fun createOrNull(string: String?): Data? {
        if (string == null) return null
        return create(string)
    }

    fun create(string: String): Data {
        return Data(StringScript.parse(string, context))
    }

    fun create(strings: List<String>): Data {
        val map = StringScript.parse(strings, context)
            .filter { "%del%" !in it }
            .flatMap { it.split("%n%") }
        return Data(map)
    }

    class Data(private val value: Any?) {

        fun isNull(): Boolean {
            return value == null
        }

        fun toInt(): Int {
            return Coerce.toInteger(value)
        }

        fun toBoolean(): Boolean {
            return Coerce.toBoolean(value)
        }

        fun toList(): List<String> {
            return value!!.asList().rebuild()
        }

        fun <T> map(transform: (Any?) -> T): List<T> {
            return (value as List<*>).map { transform(it) }
        }

        fun toShort(): Short {
            return Coerce.toShort(value)
        }

        fun toColor(): Color? {

            if (isNull()) return null

            val split = toString().split(",")
            return Color.fromRGB(Coerce.toInteger(split[0]), Coerce.toInteger(split[1]), Coerce.toInteger(split[2]))
        }

        fun toSkullTexture(): ItemBuilder.SkullTexture? {

            if (isNull()) return null

            return ItemBuilder.SkullTexture(toString(), UUID.randomUUID())
        }

        override fun toString(): String {
            return value.toString()
        }

    }

}